<?php

class EjecucionPresupuestariaController extends Zend_Controller_Action
{
    public function init()
    {
        $this->em = Zend_Registry::getInstance()->entitymanager;
    }

    //--------------------------------//
    //             PAGINA             //
    //--------------------------------//

    public function getWidth($text, Zend_Pdf_Resource_Font $font, $font_size)
    {
	$drawing_text = iconv('', 'UTF-16BE', $text);
	$characters    = array();
	for ($i = 0; $i < strlen($drawing_text); $i++) {
		$characters[] = (ord($drawing_text[$i++]) << 8) | ord ($drawing_text[$i]);
	}
	$glyphs        = $font->glyphNumbersForCharacters($characters);
	$widths        = $font->widthsForGlyphs($glyphs);
	$text_width   = (array_sum($widths) / $font->getUnitsPerEm()) * $font_size;
	return $text_width;
    }

    private function nueva_pagina($egreso, $codigoDepartamento, $nombreDepartamento)
    {
        $this->page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_LETTER);
        $this->pdf->pages[] = $this->page;
        $this->y = 660;
        $this->pagina += 1;

        $image = Zend_Pdf_Image::imageWithPath('img/logoUCA.png');
        $this->page->drawImage($image, 50, 695, ($image->getPixelWidth()+50), (695+$image->getPixelHeight()));
        $this->page->setFont($this->fontTB, 12)
                   ->drawText('Universidad Católica "Nuestra Señora de la Asunción"' ,160 ,760 ,'UTF-8');
        $this->page->setFont($this->fontT, 11)
                   ->drawText("Ejecución Presupuestaria $this->periodo" ,230 ,740 ,'UTF-8');
        if (isset($nombreDepartamento)){
            $this->page->setFont($this->fontTB, 11)
                       ->drawText('Dpto : '.$nombreDepartamento ,230 ,720 ,'UTF-8');
            $this->page->setFont($this->fontTB, 11)
                       ->drawText('Tipo : '.($egreso?'Egresos':'Ingresos') ,230 ,700 ,'UTF-8');
        }
        else{
            $this->page->setFont($this->fontTB, 11)
                       ->drawText('Tipo : '.($egreso?'Egresos':'Ingresos') ,230 ,720 ,'UTF-8');
        }
        $this->page->setFont($this->font, 9.3)
                   ->drawText('Fecha' ,467 ,770 ,'UTF-8')
                   ->drawText('Hora'  ,467 ,756 ,'UTF-8')
                   ->drawText('Página',467 ,742 ,'UTF-8')
                   ->drawText(':  '.$this->hoy->format('d/m/Y') ,500 ,770 ,'UTF-8')
                   ->drawText(':  '.$this->hoy->format('H:i:s') ,500 ,756 ,'UTF-8')
                   ->drawText(':  '.$this->pagina ,500 ,742 ,'UTF-8');
        $this->page->setFont($this->font, 10)
                   ->drawText('Código'      ,39  ,670, 'UTF-8')
                   ->drawText('Descripción' ,130 ,670, 'UTF-8')
                   ->drawText('Total'       ,345 ,670)
                   ->drawText('Realizado'   ,399 ,670)
                   ->drawText('Diferencia'  ,479 ,670)
                   ->drawText('%Ejec'       ,539 ,670);
        $this->page->setLineColor(new \Zend_Pdf_Color_Rgb(0,0,0))
                   ->drawLine(25, 684, ($this->page->getWidth()-25), 684)
                   ->drawLine(25, 664, ($this->page->getWidth()-25), 664);
    }

    private function generar($egreso, $codigoDepartamento, $nombreDepartamento, $periodo)
    {
        // obtener los rubros no terminales
        $records = $this->em->createQueryBuilder()
                ->select         ('r.codigo')
                ->addselect      ('r.egreso')
                ->addselect      ('r.terminal')
                ->addselect      ('r.nombreRubro')
                ->addselect      ('p.codigo as padre')
                ->from           ('Default_Model_Rubro',  'r')
                ->leftJoin       ('r.padre',              'p')
                ->where          ('r.terminal=false')
                ->orderBy        ('r.codigo', 'asc')
                ->getQuery       ()
                ->execute        ();

        // convertir a un array con key=codigo
        $nodos = array();

        foreach($records as $record){
            $nodos[$record['codigo']] = array(
                'codigo'      => $record['codigo'],
                'egreso'      => $record['egreso'],
                'terminal'    => $record['terminal'],
                'padre'       => $record['padre'],
                'nombreRubro' => $record['nombreRubro'],
                'montoInicial'   => 0,
                'montoEjecutado' => 0,
                'montoActual'    => 0,
                'tieneHoja'      => false
            );
        }
        unset($records);

        if (isset($codigoDepartamento))
             $whereDepartamento = "d.codigoDepartamento=$codigoDepartamento";
      //  else $whereDepartamento = '';

        // obtener las cuentas
        $hojas = $this->em->createQueryBuilder()
                ->select         ('r.codigo')
                ->addselect      ('c.montoInicial')
                ->addselect      ('c.montoEjecutado')
                ->addselect      ('c.montoActual')
                ->addselect      ('r.egreso')
                ->addselect      ('r.terminal')
                ->addselect      ('r.nombreRubro')
                ->addselect      ('p.codigo as padre')
                ->from           ('Default_Model_Cuenta', 'c')
                ->leftJoin       ('c.rubro',              'r')
                ->leftJoin       ('r.padre',              'p')
                ->leftJoin       ('c.departamento',       'd')
                ->leftJoin       ('c.presupuesto',        't')
                ->where          ('r.terminal=true')
                ->andWhere       ('r.egreso='.($egreso?'true':'false'))
                ->andWhere       ($whereDepartamento)
                ->andWhere       ("t.periodo='$periodo'")
                ->orderBy        ('p.codigo', 'asc')
                ->getQuery       ()
                ->execute        ();
        
        if (count($hojas) == 0) return;

        $this->nueva_pagina($egreso, $codigoDepartamento, $nombreDepartamento);

        // CALCULAR
        foreach ($hojas as $hoja){

            $codigo = $hoja['codigo'];

            while (($pos = strrpos($codigo, '.')) != false){

                // obtener el codigo del rubro padre
                $codigo = substr($codigo, 0, $pos);

                // sumar los montos en el padre
                if(isset($nodos[$codigo]) || $nodos[$codigo]!=null){
					$nodos[$codigo]['montoInicial']   += $hoja['montoInicial'];
					$nodos[$codigo]['montoEjecutado'] += $hoja['montoEjecutado'];
					$nodos[$codigo]['montoActual']    += $hoja['montoActual'];
					$nodos[$codigo]['tieneHoja']       = true;
				}
            }
        }

        // IMPRIMIR ROWS

        $this->y = 660;

        foreach ($nodos as $nodo){

            // si no tiene hojas, no imprime
            if ($nodo['tieneHoja']==false) continue;

            // si no entra por lo menos una hoja del nodo, nueva pagina
            if ($this->y-25-17 < 70){
                $this->nueva_pagina($egreso, $codigoDepartamento, $nombreDepartamento);
            }

            $this->y -= 25;
//35
            $nombreRubro    = substr($nodo['nombreRubro'], 0, 40);
            $montoInicial   = number_format(isset($nodo['montoInicial']  )?$nodo['montoInicial']  :0, 0, ',', '.');
            $montoEjecutado = number_format(isset($nodo['montoEjecutado'])?$nodo['montoEjecutado']:0, 0, ',', '.');
            $montoActual    = number_format(isset($nodo['montoActual']   )?$nodo['montoActual']   :0, 0, ',', '.');
            $porcentaje     = number_format($nodo['montoEjecutado']*100/$nodo['montoInicial'],        2, ',', '.');
//355 435 515 565
            $this->page->setFont($this->fontB, 7)
                 ->drawText($nodo['codigo'] ,40  ,$this->y, 'UTF-8')
                 ->drawText($nombreRubro    ,131 ,$this->y, 'UTF-8')
                 ->drawText($montoInicial   ,368-$this->getWidth($montoInicial,$this->fontB,7  ) ,$this->y)
                 ->drawText($montoEjecutado ,445-$this->getWidth($montoEjecutado,$this->fontB,7) ,$this->y)
                 ->drawText($montoActual    ,525-$this->getWidth($montoActual ,$this->fontB,7  ) ,$this->y)
                 ->drawText($porcentaje     ,565-$this->getWidth($porcentaje ,$this->fontB,7   ) ,$this->y);

            foreach ($hojas as $hoja){
                if ($hoja['padre'] == $nodo['codigo']){

                    $this->y -= 17;

                    $nombreRubro    = substr($hoja['nombreRubro'], 0, 40);
                    $montoInicial   = number_format(isset($hoja['montoInicial']  )?$hoja['montoInicial']  :0, 0, ',', '.');
                    $montoEjecutado = number_format(isset($hoja['montoEjecutado'])?$hoja['montoEjecutado']:0, 0, ',', '.');
                    $montoActual    = number_format(isset($hoja['montoActual']   )?$hoja['montoActual']   :0, 0, ',', '.');
                    $porcentaje     = number_format($hoja['montoEjecutado']*100/$hoja['montoInicial'],        2, ',', '.');
                    $this->page->setFont($this->font, 7)
                        ->drawText($hoja['codigo'] ,40  ,$this->y, 'UTF-8')
                        ->drawText($nombreRubro    ,131 ,$this->y, 'UTF-8')
                        ->drawText($montoInicial   ,368-$this->getWidth($montoInicial ,$this->fontB,7 ) ,$this->y)
                        ->drawText($montoEjecutado ,445-$this->getWidth($montoEjecutado ,$this->fontB,7) ,$this->y)
                        ->drawText($montoActual    ,525-$this->getWidth($montoActual  ,$this->fontB,7 ) ,$this->y)
                        ->drawText($porcentaje     ,565-$this->getWidth($porcentaje   ,$this->fontB,7 ) ,$this->y);
                    if ($this->y < 70){
                        $this->nueva_pagina($egreso, $codigoDepartamento, $nombreDepartamento);
                    }
                }
            }
        }
    }

    public function indexAction()
    {

        //if (X\CheckAccess::PageAction('')) return;

        try{
            // obtener los datos
            $presupuestos = $this->em->createQueryBuilder()
                    ->select         ('p.periodo')
                    ->from           ('Default_Model_Presupuesto', 'p')
                    ->orderBy        ('p.periodo', 'asc')
                    ->getQuery       ()
                    ->execute        ();

            // convertir a json
            $this->view->jsondata = Zend_Json::encode(Array(
                "success" => true,
                "total"   => count($presupuestos),
                "rows"    => $presupuestos
            ));
        }
        catch(Exception $e){
            $this->view->error = 'Error al cargar los dats.';
        }
    }

    public function departamentoAction()
    {
        // parametros a obtener
        $this->periodo = $this->_request->getQuery('periodo');
        $this->pagina = 0;
        $this->hoy = new DateTime();

        $this->pdf   = new Zend_Pdf();
        $this->font  = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
        $this->fontB = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $this->fontT = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
        $this->fontTB = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES_BOLD);

        $departamentos = $this->em->createQueryBuilder()
                ->select         ('d.codigoDepartamento')
                ->addSelect      ('d.nombreDepartamento')
                ->from           ('Default_Model_Departamento', 'd')
                ->orderBy        ('d.nombreDepartamento', 'asc')
                ->getQuery       ()
                ->execute        ();

        foreach($departamentos as $dpto){
			//INGRESO
            $this->generar     (false, $dpto['codigoDepartamento'], $dpto['nombreDepartamento'], $this->periodo);
			//EGRESO
            $this->generar     (true, $dpto['codigoDepartamento'], $dpto['nombreDepartamento'], $this->periodo);
        }

        $this->getResponse()->setHeader('Content-type', 'application/x-pdf;', true);
        $this->getResponse()->setHeader('Content-disposition', 'attatchment; filename=asdasd.pdf', true);
        $this->getResponse()->setBody($this->pdf->render());
    }

    public function rubroAction()
    {
        // parametros a obtener
        $this->periodo = $this->_request->getQuery('periodo');
        $this->pagina = 0;
        $this->hoy = new DateTime();

        $this->pdf   = new Zend_Pdf();
        $this->font  = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
        $this->fontB = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $this->fontT = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
        $this->fontTB = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES_BOLD);

        $departamentos = $this->em->createQueryBuilder()
                ->select         ('d.codigoDepartamento')
                ->addSelect      ('d.nombreDepartamento')
                ->from           ('Default_Model_Departamento', 'd')
                ->orderBy        ('d.nombreDepartamento', 'asc')
                ->getQuery       ()
                ->execute        ();

        $this->generar     (false,null,null, $this->periodo);

        
        $this->generar     (true,null,null, $this->periodo);

        $this->getResponse()->setHeader('Content-type', 'application/x-pdf;', true);
        $this->getResponse()->setHeader('Content-disposition', 'attatchment; filename=asdasd.pdf', true);
        $this->getResponse()->setBody($this->pdf->render());
    }

}


